package br.com.xti.estudo.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.regex.Pattern;

import br.com.xti.estudo.poo.Conta;


public class Arquivo3Desafio {

	private static void GravaContas(String Nome, double saldo)
	{
		Charset utf8 = StandardCharsets.UTF_8;
		Path path = Paths.get("c:/XTI/contas.txt");
		
		try {
			if(!(new File("c:/XTI/contas.txt")).exists())
			{
				Files.createDirectories(path.getParent());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	
		try{
			BufferedWriter grava = new BufferedWriter(new FileWriter(path.toString(), true));
			grava.write(Nome + " " + saldo);
			grava.newLine();
			grava.close();
			
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private static void leArquivo()
	{
		ArrayList<Conta> c1 = new ArrayList<>();
		Path path = Paths.get("c:/XTI/contas.txt");
		try(BufferedReader le = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
			String linha = null;
			String[] informacao;
			
			while ((linha = le.readLine()) != null) {
				
				//Quebro a string em 2 e converto em double para adicionar no arraylist de conta
				informacao = linha.split(Pattern.quote(" "));
				c1.add(new Conta(informacao[0],Double.parseDouble(informacao[1])));
				for (int i = 0; i < c1.size(); i++) {
					System.out.println(c1.get(i).getCliente().toString() + " Saldo " + (c1.get(i).getSaldo()));
				}
			}
			
			
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	public static void main(String[] args) {
		
		ArrayList<Conta> contas = new ArrayList<>();

		
		contas.add(new Conta("Ricardo", 12000.23));
		contas.add(new Conta("Laurence", 11050.23));
		contas.add(new Conta("Lucia", 23300.23));
		contas.add(new Conta("Beatriz", 2322.22));
		
		for (int i = 0; i < contas.size(); i++) {
			GravaContas(contas.get(i).getCliente().toString(), (contas.get(i).getSaldo()));
		}
			
		leArquivo();
		
	}

}
